<template>
  <div>
    <el-tree
      ref="refTree"
      :data="permissionData"
      :props="{ label: 'name' }"
      show-checkbox
      default-expand-all
      check-strictly
      node-key="id"
    />
    <el-button @click="hSunmit">确定</el-button>
    <el-button @click="hCancel">取消</el-button>
  </div>
</template>
<script>
// 获取权限列表
import { getPermissionList } from '@/api/permisson'
// 导入数组转树
import { tranListToTreeData } from '@/utils/index'
// 获取当前角色权限, 给角色分配权限
import { getRoleDetail, assignPerm } from '@/api/settings'
export default ({
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 取消关闭页面
    hCancel() {
      this.$emit('close')
    },
    // 获取权限信息
    async loadPermissionList() {
      const res = await getPermissionList()
      console.log(res)
      // 绑定数据进行数组转树
      this.permissionData = tranListToTreeData(res.data, '0')
      // 获取当前角色详情
      const info = await getRoleDetail(this.roleId)
      console.log(info)
      // 回填
      this.$refs.refTree.setCheckedKeys(info.data.permIds)
    },
    // 确认分配
    async hSunmit() {
      // 拿到当前选中的数据id
      const permIds = this.$refs.refTree.getCheckedKeys()
      // 更新权限信息
      const res = await assignPerm({ id: this.roleId, permIds })
      console.log(res)
      // 更新权限成功
      this.$message.success(res.message)
      // 关闭弹窗
      this.$emit('close')
    }
  }
})
</script>
